package com.yqg.manage.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yqg.manage.common.Result;
import com.yqg.manage.common.interceptor.SysLog;
import com.yqg.manage.controller.dto.*;
import com.yqg.manage.entity.*;
import com.yqg.manage.mapper.CaseMapper;
import com.yqg.manage.service.*;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * CaseController 前端控制器
 *
 * @author suzhuang
 * @since 2023-07-05
 */
@RestController
@Log4j2
@Api(tags = "案件卷宗管理")
@RequestMapping("/case")
public class CaseController {

    @Resource
    private ICaseService caseService;

    @Resource
    private IRelatedFileService relatedFileService;

    @Resource
    private IParamsService paramsService;

    @Resource
    private ICaseArchiveStageService caseArchiveStageService;

    @Resource
    private CaseMapper caseMapper;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    @SysLog("新增或者更新案件")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody Case caseInfo) {
        boolean b = false;
        try {
            // 查看案件编号是否已经存在
            LambdaQueryWrapper<Case> caseQueryWrapper = new LambdaQueryWrapper<>();
            caseQueryWrapper.eq(Case::getCaseNo, caseInfo.getCaseNo());
            if (caseInfo.getId() != null) {
                caseQueryWrapper.ne(Case::getId, caseInfo.getId());
            }
            Case one = caseService.getOne(caseQueryWrapper);
            if (one != null) {
                return Result.error("该案件编号已存在");
            }
            // 新增或修改
            if (caseInfo.getId() == null) {
                caseInfo.setEnterTime(LocalDateTime.now());
                caseInfo.setIsHanding("0");
                caseInfo.setProcess("0");
                caseInfo.setArchiveNodeId(1L);
                caseInfo.setRoutineTypeId(1L);
                ArrayList<Long> archiveBranchNodeIds = new ArrayList<>();
                caseInfo.setArchiveBranchNodeIds(archiveBranchNodeIds);
            }
            b = caseService.saveOrUpdate(caseInfo);
            //附件
            List<FileDTO> annex = caseInfo.getAnnex();
            List<RelatedFile> relatedFileList = new ArrayList<>();
            for (FileDTO fileDTO : annex) {
                if (fileDTO.getId() == null) {
                    RelatedFile relatedFile = new RelatedFile();
                    relatedFile.setCaseId(caseInfo.getId());
                    relatedFile.setFileName(fileDTO.getName());
                    relatedFile.setFilePath(fileDTO.getUrl());
                    relatedFileList.add(relatedFile);
                }
            }
            if (!relatedFileList.isEmpty()) {
                relatedFileService.saveBatch(relatedFileList);
            }
        } catch (Exception e) {
            //回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error();
        }
        return Result.success(b);
    }

    /**
     * 删除
     */
    @GetMapping("delete/{id}")
    @SysLog("删除案件")
    public Result delete(@PathVariable Integer id) {
        QueryWrapper<Case> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.eq("id", id);
        Case caseInfo = caseService.getOne(queryWrapper);
        try {
            caseInfo.setIsDelete("1");
        } catch (Exception e) {
            return Result.error("已删除");
        }
        return Result.success(caseService.saveOrUpdate(caseInfo));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public Result findAll() {
        QueryWrapper<Case> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        List<Case> list = caseService.list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(caseService.getById(id));
    }

    /**
     * 查询负责单位的全部案件
     * userId和unitId都没有就是管理员和主任
     * userId 表示找副主任负责的单位全部案件
     * unitId 表示找指定单位的全部案件
     */
    @GetMapping("/findCaseManageUnit")
    public Result findCaseManageUnit(@RequestParam Integer pageNum,
                                     @RequestParam Integer pageSize,
                                     @RequestParam(required = false) String search,
                                     @RequestParam(required = false) Long dossierId,
                                     @RequestParam String process,
                                     @RequestParam(required = false) Long userId,
                                     @RequestParam(required = false) Long unitId) {
        pageNum = (pageNum - 1) * pageSize;
        List<Case> dataList = caseMapper.findCaseManageUnit(pageNum, pageSize, search, dossierId, process, userId, unitId);
        Integer count = caseMapper.findCaseManageUnitCount(search, dossierId, process, userId, unitId);
        Map<String, Object> map = new HashMap<>();
        map.put("records", dataList);
        map.put("total", count);
        return Result.success(map);
    }

    /**
     * 查询指向自己的案件
     * userId 表示找指向自己的案件
     */
    @GetMapping("/findCasePointToUser")
    public Result findCasePointToUser(@RequestParam Integer pageNum,
                                      @RequestParam Integer pageSize,
                                      @RequestParam(required = false) String search,
                                      @RequestParam(required = false) Long dossierId,
                                      @RequestParam String process,
                                      @RequestParam Long userId,
                                      @RequestParam(required = false) Long unitId) {
        pageNum = (pageNum - 1) * pageSize;
        List<Case> dataList = caseMapper.findCasePointToUser(pageNum, pageSize, search, dossierId, process, userId, unitId);
        Integer count = caseMapper.findCasePointToUserCount(search, dossierId, process, userId, unitId);
        Map<String, Object> map = new HashMap<>();
        map.put("records", dataList);
        map.put("total", count);
        return Result.success(map);
    }


    /**
     * 驳回案件
     */
    @GetMapping("caseBack")
    public Result caseBack(@RequestParam Long id,
                           @RequestParam String backReason,
                           @RequestParam String process) {
        Case oneCase = caseService.getById(id);
        oneCase.setBackReason(backReason);
        oneCase.setProcess(process);
        // 驳回将本案的所有文书判断，不为4（已通过）状态全部都设置1
        paramsService.updateStatusByCaseId(id, "0", Arrays.asList("1", "2", "3", "5", "6", "7"));
        return Result.success(caseService.saveOrUpdate(oneCase));
    }

    /**
     * 提交之前判断本案文书下的状态是否有没有未通过的文书
     *
     * @return 有true, 无false
     */
    @GetMapping("/submitBeforeJudgmentStatus")
    public Result submitBeforeJudgmentStatus(@RequestParam Long caseId,
                                             @RequestParam List<String> status) {
        return Result.success(paramsService.getUnfinished(caseId, status));
    }

    /**
     * 案件提交(不包括领导审批)
     *
     * @param caseInfo 参数信息
     */
    @PostMapping("/submitCheck")
    public Result submitCheck(@RequestBody SubmitCheckCaseDTO caseInfo) {
        Case aCase = caseService.getById(caseInfo.getId());
        String process = caseInfo.getProcess();
        if (process == null || aCase == null) {
            return Result.error("系统错误");
        }
//        判断提交到哪的过程
        switch (process) {
            case "1":
//        承办人提交到科室待审核
                aCase.setSquadronLeader(caseInfo.getUserId());
                aCase.setTransactorExplain(caseInfo.getExplain());
                paramsService.updateStatusByCaseId(caseInfo.getId(), "1", Collections.singletonList("0"));

                if (aCase.getIsHanding().equals("0")) {
//                第一次提交设置办理等信息
                    aCase.setIsHanding("1");
                    aCase.setDealCreate(LocalDateTime.now());
                } else if (aCase.getIsHanding().equals("1")) {
//                    清空各种提交信息
                    caseMapper.setCommitInfoToNull(aCase.getId());
                    aCase.setSquadronLeaderExplain(null);
                    aCase.setLawDepartment(null);
                    aCase.setLawDepartmentExplain(null);
                    aCase.setDirector(null);
                    aCase.setDirectorExplain(null);
                    aCase.setService(null);
                    aCase.setServiceExplain(null);
                    aCase.setLeader(null);
                    aCase.setBackReason(null);
                }
                aCase.setProcess(process);

                break;
            case "3":
//        中队长提交到法律待审核
                aCase.setLawDepartment(caseInfo.getUserId());
                aCase.setSquadronLeaderExplain(caseInfo.getExplain());
                aCase.setProcess(process);
                break;
            case "5":
//        法规科或中队长提交到部门待审核
                if (aCase.getProcess().equals("1")) {
                    aCase.setSquadronLeaderExplain(caseInfo.getExplain());
                } else {
                    aCase.setLawDepartmentExplain(caseInfo.getExplain());
                }
                aCase.setProcess(process);
                break;
            case "7":
//        局长提交到服务中心待审核
//            设置局长ID
                aCase.setDirector(caseInfo.getLoginUserId());
                aCase.setService(caseInfo.getUserId());
                aCase.setDirectorExplain(caseInfo.getExplain());
                aCase.setProcess(process);
                break;
            case "9":
//        局长或服务中心提交到领导待审核
                if (aCase.getProcess().equals("5")) {
//                局长直接提交到领导待审核，设置局长ID
                    aCase.setDirector(caseInfo.getLoginUserId());
                    aCase.setDirectorExplain(caseInfo.getExplain());
                } else {
                    aCase.setServiceExplain(caseInfo.getExplain());
                }
                aCase.setProcess(process);
                break;
            default:
                return Result.error("系统错误");
        }

        return Result.success(caseService.saveOrUpdate(aCase));
    }

    /**
     * 审批通过
     */
    @PostMapping("/caseApprovePass")
    public Result caseApprovePass(@RequestBody SubmitCheckCaseDTO caseInfo) {
        Case aCase = caseService.getById(caseInfo.getId());
        Boolean b = caseService.isCaseClosed(caseInfo.getId());
        if (b) {
            //  结案
            if (aCase.getProcess().equals("9")) {
                // 领导结案提交的
                aCase.setLeader(caseInfo.getLoginUserId());
            } else if (aCase.getProcess().equals("5")) {
                // 局长提交的
                aCase.setDirector(caseInfo.getLoginUserId());
            }
            aCase.setProcess("11");
            // 设置办理等信息
            aCase.setIsHanding("2");

        } else {
            // 不结案
            if (aCase.getProcess().equals("9")) {
                // 领导结案提交的
                aCase.setLeader(caseInfo.getLoginUserId());
            } else if (aCase.getProcess().equals("5")) {
                // 局长提交的
                aCase.setDirector(caseInfo.getLoginUserId());


            }
            //  重新开始一轮提交
            aCase.setProcess("0");
        }
        // 修改文书暂时通过（7）状态为通过（4）状态
        paramsService.updateStatusByCaseId(caseInfo.getId(), "4", Collections.singletonList("7"));
        return Result.success(caseService.saveOrUpdate(aCase));
    }


    /**
     * 统计案件是否办理（2已完结，1办理中，0待办理，）
     */
    @GetMapping("/handing")
    public Result countHanding(@RequestParam(required = false) Long unitId,
                               @RequestParam(required = false) Long userId) {
        HandingDTO[] handingDTO = caseService.handing(unitId, userId);
        return Result.success(handingDTO);
    }

    /**
     * 案件来源统计
     *
     * @return
     */
    @GetMapping("/inform")
    public Result countInform(@RequestParam(required = false) Long unitId,
                              @RequestParam(required = false) Long userId) {
        InformDTO[] informDTOS = caseService.inform(unitId,userId);
        return Result.success(informDTOS);
    }

    /**
     * 案件分类排行
     *
     * @return
     */
    @GetMapping("/typeRanking")
    public Result countCaseType(@RequestParam(required = false) Long unitId,
                                @RequestParam(required = false) Long userId) {
        CaseCategoryRankingDTO[] caseCategoryRankingDTO = caseService.caseTypeRanking(unitId,userId);
        return Result.success(caseCategoryRankingDTO);
    }

    /**
     * 案件处理结果统计
     *
     * @return
     */
    @GetMapping("/result")
    public Result countResult(@RequestParam(required = false) Long unitId,
                              @RequestParam(required = false) Long userId) {
        CaseResultDTO[] caseResultDTOS = caseService.countResult(unitId,userId);
        return Result.success(caseResultDTOS);
    }

    /**
     * 年度案件办理数量 按月统计 以办理时间为准
     *
     * @param month 前几个月
     */
    @GetMapping("/monthCount")
    public Result monthCount(@RequestParam Long month,
                             @RequestParam(required = false) Long unitId,
                             @RequestParam(required = false) Long userId) {
        List<MontCountDTO> montCountDTOS;
        try {
            montCountDTOS = caseService.monthCount(month, unitId, userId);
        } catch (Exception e) {
            return Result.error("查询失败");
        }
        return Result.success(montCountDTOS);
    }

    /**
     * 生成案件编号yyyyMMddHHmmss
     */
    @GetMapping("/caseNum")
    @ApiOperation("生成案件编号，一秒调用一次内种")
    public synchronized Result caseNum() {
        return Result.success(caseService.num());
    }

    /**
     * 判断编号是否存在
     */
    @GetMapping("ifExist")
    public Result ifExist(String caseNum) {
        try {
            caseService.ifExist(caseNum);
        } catch (Exception e) {
            return Result.success(false);
        }
        return Result.success(true);
    }
}

